import lrc from './data.js';
import {
  analysisLrc
} from './utils/index.js';

let audioObj = {
  ul: document.querySelector('.container ul'), // 歌词列表
  audio: document.querySelector('audio'), // 音频
  container: document.querySelector('.container'), // 播放器容器
}
let musicObj = []; // 音乐数据
 
/**
 * 获取当前的播放时间
 * @returns
 */
const getAudioTime = () => {
  return audioObj.audio.currentTime;
}
 
const addMusic = () => {
  let documentFragment = document.createDocumentFragment();
  for(let i = 0; i < musicObj.length; i++){
    let li = document.createElement('li');
    li.textContent = musicObj[i].value;
    documentFragment.appendChild(li);
  }
  audioObj.ul.appendChild(documentFragment);
}
 
// 根据时间来获取当前需要显示的条数
const getMusicIndex = () => {
  let time = getAudioTime();
  for(let i = 0;i < musicObj.length; i++) {
    let musicTime = musicObj[i].time;
    if(time < musicTime){
      return i-1;
    }
  }
  return musicObj.length - 1;
}
// 移动...
let currentIndex = 0;
const move = () => {
  currentIndex = getMusicIndex(); //当前高亮的歌词下标
  let containerHeight = audioObj.container.clientHeight; //Container高度
  let liHeight = audioObj.ul.children[0].clientHeight; // 每个li标签的高度
  let movePx = liHeight * currentIndex + liHeight/2 - containerHeight/2; //需要移动的
  let maxMove = audioObj.ul.clientHeight - containerHeight/2;
  // 范围判断
  if(movePx < 0){
      movePx = 0;
  }
  if(movePx > maxMove){
      movePx = maxMove;
  }
  // 取消前面的高亮
  let activeLi = audioObj.ul.querySelector('.active');
  if(activeLi){
      activeLi.classList.remove("active");
  }
  // 实现高亮
  let currentLi = audioObj.ul.children[currentIndex];
  if(currentLi){
      currentLi.classList.add('active');
  }
  // 移动
  audioObj.ul.style.transform = `translateY(-${movePx}px)`;
}
audioObj.audio.addEventListener('timeupdate', move);
 
const init = () => {
  // 解析歌词数据
  musicObj = analysisLrc(lrc);
  console.log(musicObj);
  // 插入歌词
  addMusic();
}

init(); //入口函数
